<template>
  <div class="flex-box">
    <div class="input_t">
      <el-input v-model="classname" placeholder="请输入班级名称" style="width: 200px;margin-right: 10px" clearable></el-input>
      <el-input v-model="title" placeholder="请输入作业名称" style="width: 200px;margin-right: 10px" clearable></el-input>
    </div>
    <div class="button_t">
      <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
      <el-button @click="addHomework" type="primary">添加作业</el-button>
    </div>
  </div>
  <div class="el_center">
    <el-table
        :data="homeworkData"
        border
        style="width: 100%">
      <el-table-column label="序号" width="80" align="center">
        <template #default="scope">
          {{ (currentPage - 1) * pagesize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        label="标题"
        prop="title"
        align="center"
        header-align="center"
      ></el-table-column>
      <el-table-column
          label="描述"
          prop="description"
          align="center"
          header-align="center"
      ></el-table-column>
      <el-table-column
          label="截止时间"
          prop="deadline"
          align="center"
          header-align="center"
      ></el-table-column>
      <el-table-column
          label="班级"
          prop="className"
          align="center"
          header-align="center"
      ></el-table-column>
      <el-table-column
          label="教师"
          prop="teacherName"
          align="center"
          header-align="center"
      ></el-table-column>
      <el-table-column
          label="学生人数"
          prop="studentNum"
          width="150"
          align="center"
          header-align="center"
      ></el-table-column>
      <el-table-column
        label="题目具体要求"
        prop="content"
        width="150"
        align="center"
        header-align="center"
      >
        <template #default="scope">
          <el-button type="text" @click="downloadFile(scope.row.homeworkId)">下载</el-button>
        </template>
      </el-table-column>
      <el-table-column
          label="操作"
          width="180"
          align="center"
          header-align="center"
      >
        <template #default="scope">
          <el-button type="primary" @click="homeworkEdit(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
      <el-table-column
          type="expand"
          label="学生提交"
          width="180"
          align="center"
          header-align="center"
      >
        <template #default="props">
          <el-table :data="props.row.homeworkStudentList" border style="width: 100%">
            <el-table-column label="序号" width="80" align="center">
              <template #default="scope">
                {{ (currentPage - 1) * pagesize + scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column
                label="学生姓名"
                prop="studentName"
                align="center"
                header-align="center"
            ></el-table-column>
            <el-table-column
                label="提交时间"
                prop="submittedAt"
                align="center"
                header-align="center"
            ></el-table-column>
            <el-table-column
                label="提交内容"
                prop="content"
                align="center"
                header-align="center"
            >
              <template #default="scope">
                <el-button type="text" @click="downloadsub(scope.row.submissionId)">下载</el-button>
              </template>
            </el-table-column>
            <el-table-column
                label="分数"
                prop="score"
                align="center"
                header-align="center"
            ></el-table-column>
            <el-table-column
                label="反馈"
                prop="feedback"
                align="center"
                header-align="center"
            ></el-table-column>

            <el-table-column
                label="操作"
                width="180"
                align="center"
                header-align="center"
            >
              <template #default="scope">
                <el-button type="primary" @click="homeworkStudentEdit(scope.row)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>

      </el-table-column>
    </el-table>
  </div>
  <div class="el_center">
    <el-pagination
        v-model:current-page="pageno"
        v-model:page-size="pagesize"
        :page-sizes="[10, 20, 40, 50]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <el-dialog
      v-model="dialogVisible"
      :title="diaTitle"
      width="500"
      :before-close="handleClose"
  >
    <el-form :model="homeworkinfo" label-width="auto" style="max-width: 600px">
      <el-form-item
          label="作业名称"
          prop="title"
          :rules="[{ required: true, message: '作业名称不能为空', trigger: 'blur' }]"
      >
        <el-input v-model="homeworkinfo.title" placeholder="请输入作业名称" style="width: 200px;margin-right: 10px" clearable></el-input>
      </el-form-item>
      <el-form-item
          label="作业描述"
          prop="description"
          :rules="[{ required: true, message: '作业描述不能为空', trigger: 'blur' }]"
      >
        <el-input v-model="homeworkinfo.description" placeholder="请输入作业描述" style="width: 200px;margin-right: 10px" clearable></el-input>
      </el-form-item>
      <el-form-item
          label="截止时间"
          prop="deadline"
          :rules="[{ required: true, message: '截止时间不能为空', trigger: 'blur' }]"
      >
          <el-date-picker
              v-model="homeworkinfo.deadline"
              type="datetime"
              placeholder="选择作业截至日期"
              :shortcuts="shortcuts"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
      </el-form-item>
      <el-form-item label="班级">
        <el-select
            v-model="homeworkinfo.className"
            filterable
            placeholder="请选择班级"
            style="width: 240px"
        >
          <el-option
              v-for="item in classList"
              :key="item.classId"
              :label="item.name"
              :value="item.classId"
          />
        </el-select>
      </el-form-item>
      <el-form-item
          label="详细要求文件"
          prop="content"
      >
        <el-upload
            class="upload-demo"
            drag
            action
            multiple
            :http-request="uploadfile"
            :data="file"
            :on-success="handleSuccess"
            :on-error="handleError"
            :before-upload="beforeUpload"
            :limit="1"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将文件拖至这里或 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              文件大小不超过 5M，支持上传 PDF、Word、Excel 等文件
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <div>
      <el-button type="primary" @click="confirm">确定</el-button>
      <el-button @click="dialogVisible = false">取消</el-button>
    </div>
  </el-dialog>
  <el-dialog
      v-model="dialogVisibleSubmit"
      title="编辑学生作业信息"
      width="500"
      :before-close="handleCloseSubmit"
  >
    <el-form :model="studentinfo" label-width="auto" style="max-width: 600px">
      <el-form-item
          label="老师点评"
          prop="feedback"
          :rules="[{ required: true, message: '点评不能为空', trigger: 'blur' }]"
      >
        <el-input v-model="studentinfo.feedback" placeholder="请输入老师的点评" style="width: 200px;margin-right: 10px" clearable></el-input>
      </el-form-item>
      <el-form-item
          label="分数"
          prop="score"
          :rules="[{ required: true, message: '分数不能为空', trigger: 'blur' }]"
      >
        <el-input v-model="studentinfo.score" placeholder="输入正确的分数" style="width: 200px;margin-right: 10px" clearable></el-input>
      </el-form-item>
      <el-form-item
          label="作业文件"
          prop="content"
      >
        <el-upload
            class="upload-demo"
            drag
            action
            multiple
            :http-request="uploadfile"
            :data="file"
            :on-success="handleSuccess"
            :on-error="handleError"
            :before-upload="beforeUpload"
            :limit="1"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将文件拖至这里或 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              文件大小不超过 5M，支持上传 PDF、Word、Excel 等文件
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="confirmSubmit">确定</el-button>
        <el-button @click="dialogVisibleSubmit = false,studentinfo = {}">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script setup>
import {ref,onMounted} from 'vue'
import {Search,GetClassList,UpdateHomework,AddHomework,UpdateSubmission} from "../../../api/homework"
import {ElMessage} from "element-plus";
import dayjs from 'dayjs';
import {renderAsync} from "docx-preview";
import axios from "axios";

const currentPage = ref(1)
const classname = ref('')
const title = ref('')
const homeworkinfo=ref({
  homeworkId: '',
  title: "",
  description: "",
  deadline: "",
  className:'',
  classId: '',
  content:''
})
const homeworkData = ref([{
  homeworkId: '',
  title: "",
  description: "",
  deadline: "",
  createdAt: "",
  content: "",
  classId: "",
  className: "",
  teacherId: "",
  teacherName: "",
  deletedAt: '',
  studentNum: '',
  homeworkStudentList: [
    {
      submissionId: "",
      studentId: "",
      studentName: "",
      content: "",
      score: '',
      feedback: '',
      submittedAt: "",
      homeworkId: ''
    }
  ]
}])
const pageno = ref(1)
const pagesize = ref(10)
const total = ref(0)
const size = ref(false)
const disabled = ref(false)
const background = ref(false)
const dialogVisible = ref(false)
const dialogVisibleSubmit = ref(false)
const isAdd = ref(false)
const diaTitle = ref('')
const classList=ref([{
  name: '',
  classId: ''
}])
const studentinfo = ref({
  submissionId: "",
  studentId: "",
  studentName: "",
  content: "",
  score: '',
  feedback: '',
  submittedAt: "",
  homeworkId: ''
})

const handleSizeChange = (val) => {
  pagesize.value = val
  search()
}
const handleCurrentChange = (val) => {
  pageno.value = val
  search()
}
const handleClose = (done) => {
  homeworkinfo.value = {}
  dialogVisible.value = false
  done()
}
const handleCloseSubmit = (done) => {
  studentinfo.value = {}
  dialogVisibleSubmit.value = false
  done()
}
const search = () => {
  Search({
    classname:classname.value,
    title:title.value,
    pageno:pageno.value,
    pagesize:pagesize.value
  }).then(res=>{
    homeworkData.value = res.data.data.records
    total.value=res.data.data.total
  })
}
const getClassList = () => {
  GetClassList().then(res=>{
    classList.value = res.data.data
  })
}
const addHomework = () => {
  getClassList()
  diaTitle.value = '新增作业'
  isAdd.value = true
  dialogVisible.value = true
}
const homeworkEdit = (row) => {
  getClassList()
  homeworkinfo.value = row
  diaTitle.value = '编辑作业'
  isAdd.value = false
  dialogVisible.value = true
}
const homeworkStudentEdit = (row) => {
  studentinfo.value = row
  dialogVisibleSubmit.value = true
}
const file = ref(null)

// 更健壮的上传处理方法
const uploadfile = (options) => {
  // 验证文件对象有效性
  if (options.file instanceof File) {
    file.value = options.file
    console.log('接收到的文件:', {
      name: options.file.name,
      size: options.file.size,
      type: options.file.type
    })
  } else {
    ElMessage.error('无效的文件对象')
    file.value = null
  }
}

const confirm = async () => {
  dialogVisible.value = false

  // 校验必填字段
  if (!validateForm()) return

  // 构建 FormData（优化版）
  const formData = buildFormData()

  try {
    const apiMethod = isAdd.value ? AddHomework : UpdateHomework
    await apiMethod(formData)

    ElMessage.success(isAdd.value ? '新增成功' : '更新成功')
    homeworkinfo.value = {}
    search()
  } catch (error) {
    ElMessage.error(`操作失败: ${error.message}`)
  }
}
const confirmSubmit =async () => {
  dialogVisibleSubmit.value = false

  // 校验必填字段
  if (!validateForm()) return

  // 构建 FormData（优化版）
  const formData = buildFormDataSub()

  try {
    const apiMethod = UpdateSubmission
    await apiMethod(formData)

    ElMessage.success('更新成功')
    studentinfo.value = {}
    search()
  } catch (error) {
    ElMessage.error(`操作失败: ${error.message}`)
  }
}

// 表单验证方法
const validateForm = () => {
  if (!file.value) {
    ElMessage.error('请上传文件')
    return false
  }


  return true
}
const buildFormDataSub = () => {
  const formData = new FormData()
  const fields={
    submissionId: studentinfo.value.submissionId,
    feedback: studentinfo.value.feedback,
    score: studentinfo.value.score,
  }
  Object.entries(fields).forEach(([key, value]) => {
    if (value !== undefined) {
      formData.append(key, value)
    }
  })

  // 文件字段（强制校验）
  if (file.value instanceof File) {
    formData.append('content', file.value, file.value.name) // 第三个参数指定文件名
  }

  return formData
}
// 构建 FormData 方法
const buildFormData = () => {
  const formData = new FormData()
  // 文本字段（需处理空值情况）
  const fields = {
    homeworkId: !isAdd.value ? homeworkinfo.value.homeworkId : undefined,
    title: homeworkinfo.value.title,
    description: homeworkinfo.value.description,
    deadline: homeworkinfo.value.deadline,
    classId: homeworkinfo.value.className
  }

  Object.entries(fields).forEach(([key, value]) => {
    if (value !== undefined) {
      formData.append(key, value)
    }
  })

  // 文件字段（强制校验）
  if (file.value instanceof File) {
    formData.append('content', file.value, file.value.name) // 第三个参数指定文件名
  }

  return formData
}

const shortcuts = [
  {
    text: '今天',
    value: new Date(),
  },
  {
    text: '明天',
    value: () => {
      const date = new Date()
      date.setDate(date.getDate() + 1)
      return date
    },
  },
  {
    text: '下周',
    value: () => {
      const date = new Date()
      date.setDate(date.getDate() + 7)
      return date
    },
  },
]
const handleSuccess=(response, file, fileList)=> {
  console.log('上传成功:', response);
  // 根据响应处理逻辑
}
const handleError=(error, file, fileList)=> {
  console.error('上传失败:', error);
}
const beforeUpload=(file)=> {
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    this.$message.error('文件大小不能超过 5MB!');
  }
  return isLt5M;
}
// 下载文件
import request from '../../../utils/request.js';
const downloadFile = async (id) => {
  try {
    const response = await request.get(`/homework/download/${id}`, {
      responseType: 'blob',
      params: { t: Date.now() } // 强制刷新
    });

    // 解析RFC 5987编码的文件名
    const contentDisposition = response.headers['content-disposition'];
    let fileName = 'file';
    if (contentDisposition) {
      const utf8FilenameRegex = /filename\*=UTF-8''([^;]+)/i;
      const matches = utf8FilenameRegex.exec(contentDisposition);
      fileName = matches ? decodeURIComponent(matches[1]) :
          contentDisposition.split('filename=')[1].replace(/["']/g, '');
    }

    // 创建Blob时指定MIME类型
    const blob = new Blob([response.data], {
      type: response.headers['content-type'] || 'application/octet-stream'
    });

    // 创建隐藏链接触发下载
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    URL.revokeObjectURL(link.href);
    document.body.removeChild(link);
  } catch (error) {
    console.error('下载失败:', error);
    // 显示错误提示
  }
};
const downloadsub = async (id) => {
  try {
    const response = await request.get(`/submission/download/${id}`, {
      responseType: 'blob',
      params: { t: Date.now() } // 强制刷新
    });

    // 解析RFC 5987编码的文件名
    const contentDisposition = response.headers['content-disposition'];
    let fileName = 'file';
    if (contentDisposition) {
      const utf8FilenameRegex = /filename\*=UTF-8''([^;]+)/i;
      const matches = utf8FilenameRegex.exec(contentDisposition);
      fileName = matches ? decodeURIComponent(matches[1]) :
          contentDisposition.split('filename=')[1].replace(/["']/g, '');
    }

    // 创建Blob时指定MIME类型
    const blob = new Blob([response.data], {
      type: response.headers['content-type'] || 'application/octet-stream'
    });

    // 创建隐藏链接触发下载
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    URL.revokeObjectURL(link.href);
    document.body.removeChild(link);
  } catch (error) {
    console.error('下载失败:', error);
    // 显示错误提示
  }
}
onMounted(()=>{
  search()
})
</script>
<style lang="less" scoped>
.flex-box {
  display: flex;
  justify-content: space-between;
}
.el_center {
  display: flex;
  justify-content: center;
}
</style>
